/**
 * @Description:
 * @Author BPF
 * @create 2021/8/24 13:59
 */
import axios from 'axios'
import { message } from 'ant-design-vue'
import { Base64 } from 'js-base64'
import appConfig from '/src/config/index'
import { get, sync, call } from '~vuex-helper'

// 创建axios实例
const instance = axios.create({
  timeout: 10000 // 请求超时时间
})

instance.defaults.headers.post['Content-Type'] = 'application/json' // 'application/json';
instance.defaults.baseURL = ''

// request拦截器
instance.interceptors.request.use(
  config => {
    console.log('方法:', config.method)
    console.log('接口:', config.url)
    console.log('参数:', config.data || 'null')
    const accessToken_ = get('user/accessToken')
    const tokenType_ = get('user/tokenType')
    return {
      ...config,
      headers: {
        Authorization:
          (accessToken_?.value && `${tokenType_.value} ${accessToken_.value}`) ||
          'Basic ' + Base64.encode(appConfig.client_id + ':' + appConfig.client_secret),
        ...config.headers
      }
    }
  },
  error => {
    return Promise.reject(error)
  }
)

// response 拦截器
instance.interceptors.response.use(
  response => {
    console.log('服务器返回:', response.data)
    const res = response.data
    if (res.code === '401' || res.code === 401 || res.error == 'unauthorized') {
      message.error('登录已过期, 请重新登录')
      return Promise.reject('error')
    } else {
      return res
    }
  },
  error => {
    console.log('服务器error:', error.toString(), String(error))
    if (String(error).includes('401')) {
      message.error('登录已过期, 请重新登录')
      call('user/logOut')?.()
    } else if (String(error).includes('timeout')) {
      message.error('网络连接超时')
    }
    const loading_ = sync('app/loading')
    loading_.value = false
    return Promise.reject(error)
  }
)

export const POST = ({ url, params = {}, data = {}, headers = {}, ...others }) =>
  instance({ url, method: 'POST', data, params, headers, ...others })

export const GET = ({ url, params = {}, data = {}, headers = {}, ...others }) =>
  instance({ url, method: 'GET', data, params, headers, ...others })
